<template>
	<s-layout title="销售订单">
		<su-sticky bgColor="#fff">
			<su-tabs :list="tabs" :scrollable="false" @change="changeTab" :current="activeTab" />
		</su-sticky> 
		
		<view>
			<!-- 查询条件 -->
			<view class="filters">
			    <view @click="toggleFilters" class="filter-header">
			        <text>查询条件</text>
			        <text>{{ showFilters ? '收起' : '展开' }}</text>
			    </view>
			    <view v-show="showFilters" class="filter-body">
			        <input class="filter-input" v-model="query.name" placeholder="请输入关键字" />
			        <input class="filter-input" v-model="query.no" placeholder="请输入订单单号" />
			        <picker class="filter-input" mode="selector" :range="customerNames" @change="onCustomerChange" :value="customerIndex">
			            <view class="pickercustomer">{{ customerNames[customerIndex] || '请选择客户' }}</view>
			        </picker>
			        <view class="item-actions-inline">
			            <button @click="search()" class="action-button">查询</button>
			            <button @click="reset()" class="action-button danger">重置</button>
			        </view>
			    </view>
			</view>
			
			<!-- 浮动按钮 -->
			<view class="floating-button" @click="onFloatingButtonClick">
			    <image src="/static/images/icon/toadd.png" class="icon-img" mode="aspectFit" />
			</view>
			<view class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20" v-for="item in listData"
				:key="item.id">
				<view @click="viewDetails(item)">
					<view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20 ">
						<view class="order-no">编号：{{ item.no }}</view>
						{{ getStatusText(item.status) }}
					</view>
					<view class="ss-p-x-20 ">
						<view>客户：{{ item.customerName }}</view>
						<view>产品：{{ item.productNames }}</view>
						<view>订单时间：{{ item.orderTime }}</view>
						<view>总数量：{{ item.totalCount }}</view>
						<view>出库数：{{ item.outCount }}</view>
						<view>金额：{{ item.totalProductPrice }}</view>
						<view>退货数：{{ item.returnCount }}</view> 
					</view>
				</view>
				<view class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
					<view class="ss-flex ss-col-center">
						<view class="discounts-title pay-color">总金额:</view>
						<view class="discounts-money pay-color">￥{{ item.totalProductPrice }}</view>
					</view>
				</view>	
					<view class="order-card-footer ss-flex ss-col-center ss-p-x-20">
					<button @click="editItem(item)" class="action-button">出库</button>
					<button @click="editItem(item)" class="action-button">开票</button>
					<button @click="editItem(item)" class="action-button">付款</button>
					<button @click="updateStatus(item.id,'20')" class="action-button">审核</button>
					<button @click="updateStatus(item.id,'10')" class="action-button">反审核</button>
					<button @click="editItem(item)" class="action-button">修改</button>
					<button @click="deleteItem(item)" class="action-button danger">删除</button>
					
				</view>
				<view class="divider"></view>
			</view>
		</view>

		<uni-load-more v-if="listData.length > 0" :status="loading ? 'loading' : (hasMoreData ? 'more' : 'noMore')"
			:content-text="{
        contentdown: '上拉加载更多',
      }" @tap="loadMoreData" />
	</s-layout>
</template>

<script>
	import {
		getCustomers,
		pageList,
		deleteOrders,
		updateSaleOrderStatus,
	} from "@/sheep/api/erp/order.js";

export default {
    data() {
        return {
            tabs: [
                { id: 10, name: '未审核', count: 3 },
                { id: 20, name: '已审核', count: 2 },
                { id: 30, name: '待发货', count: 1 },
                { id: 40, name: '已发货', count: 1 },
                { id: 50, name: '待付款', count: 2 },
                { id: 60, name: '已付款', count: 2 }
            ],
            activeTab: 0,
            showFilters: false,
            query: {
                name: '',
                no: '',
                customerId: '',
                remark: ''
            },
            listData: [],
            customerIndex: -1,
            customers: [],
            pageNum: 1,
            pageSize: 10,
            loading: false,
            hasMoreData: true
        };
    },
    computed: {
        customerNames() {
            return this.customers.map(customer => customer.name);
        }
    },
    methods: {
        getStatusClass(status) { 
            const statusMap = {
                10: 'unaudited',
                20: 'audited',
                30: 'unshipped',
                40: 'shipped',
                50: 'unpaid',
                60: 'paid'
            };
            return statusMap[status] || '';
        },
        getStatusText(status) { 
            const statusTextMap = {
                10: '未审核',
                20: '已审核',
                30: '待发货',
                40: '已发货',
                50: '待付款',
                60: '已付款'
            };
            return statusTextMap[status] || '未知状态';
        },
        // 切换标签
        changeTab(index) {
            this.activeTab = index;
            this.refreshData();
        },
        // 切换查询条件显示
        toggleFilters() {
            this.showFilters = !this.showFilters;
        },
        onCustomerChange(e) {
            this.customerIndex = parseInt(e.detail.value, 10);
            if (this.customerIndex !== -1) {
                this.query.customerId = this.customers[this.customerIndex].id;
                this.refreshData();
            }
        },
        reset() {
            this.query = {
                name: '',
                no: '',
                customerId: '',
                remark: ''
            };
            this.customerIndex = -1;
            this.refreshData();
        },
        search() {
            this.refreshData();
        },
        refreshData() {
            this.pageNum = 1;
            this.hasMoreData = true;
            this.listData = [];
            this.loadMoreData();
        },
        async fetchCustomers() {
            try {
                const res = await getCustomers();
                this.customers = res.data;
            } catch (error) {
                this.showToast("获取客户数据失败");
            }
        },
        async loadMoreData() {
            if (this.loading || !this.hasMoreData) return;

            this.loading = true;
            const params = {
                status: this.tabs[this.activeTab]?.id,
                pageNo: this.pageNum,
                pageSize: this.pageSize,
                ...this.query
            };
            try {
                const res = await pageList(params);
                const { list, total } = res.data;
                if (this.pageNum * this.pageSize >= total) {
                    this.hasMoreData = false;
                }
                this.listData = [...this.listData, ...list];
            } catch (error) {
                console.error('加载数据失败:', error);
            } finally {
                this.loading = false;
                uni.stopPullDownRefresh();
            }
        },
        onPullDownRefresh() {
            this.refreshData();
			setTimeout(function() {
				 this.loading = false;
				uni.stopPullDownRefresh();
			}, 800);
        },
        onReachBottom() {
            if (!this.hasMoreData) return;
            this.pageNum++;
            this.loadMoreData();
        },
        onFloatingButtonClick() {
            uni.setStorageSync('orderId', '');
            uni.navigateTo({
                url: '/pages/erp/sale/edit'
            });
        },
        async updateStatus(id, status) {
            try {
                await updateSaleOrderStatus(id, status);
                this.showToast("提交成功", "success");
                this.refreshData();
            } catch (error) {
                this.showToast("提交失败:" + error.msg);
            }
        },
        // 详情、编辑、删除
        viewDetails(item) {
            const orderId = encodeURIComponent(item.id);
            uni.setStorageSync('orderId', orderId);
            uni.navigateTo({
                url: "/pages/erp/sale/show"
            });
        },
        editItem(item) {
            const orderId = encodeURIComponent(item.id);
            uni.setStorageSync('orderId', orderId);
            uni.navigateTo({
                url: "/pages/erp/sale/edit"
            });
        },
        async deleteItem(item) {
            try {
                if (item.id) {
                    await deleteOrders(item.id);
                    this.refreshData();
                }
            } catch (error) {
                console.error('订单删除失败:', error);
            }
        }
    },
    onLoad() {
        uni.setStorageSync('orderId', '');
        this.refreshData();
        this.fetchCustomers();
    },
    onShow() {
        // 如果需要刷新数据，例如返回页面后
        if (this.needsRefresh) {
            this.refreshData();
            this.needsRefresh = false;
        }
        this.fetchCustomers();
    }
};
</script>

<style lang="scss" scoped>
	.divider {
	  border-top: 1px solid #c5c5c5;
	  margin: 10px 0;
	}
	.order-details {

		border-radius: 30rpx;
		margin-right: 10rpx;
	}

/* 操作按钮样式 */
.item-actions-inline {
  display: flex;
  justify-content: flex-start;
  gap: 5px;
}

/* 浮动按钮样式 */
.floating-button {
  position: fixed;
  bottom: 60px;
  right: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
/* 查询条件样式 */
.filters {
  margin: 5px;
  background-color: #fff;
  border-radius: 5px;
  padding: 8px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #333;
}

.filter-body {
  margin-top: 10px;
}

.filter-input {
  width: 100%;
  height: 50rpx;
  padding: 3px;
  font-size: 14px;
  margin-bottom: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

	.action-button {
		height: 25px;
		width: 45px;
		line-height: 25px;
		text-align: center;
		font-size: 14px;
		border-radius: 3px;
		background-color: #2e70fc;
		color: #fff;
		border: none;
		cursor: pointer;
		transition: background-color 0.3s ease;
		padding: 1px 3px;
	}

	.delete-btn {
		width: 160rpx;
		height: 56rpx;
		color: #ff3000;
		background: #fee;
		border-radius: 28rpx;
		font-size: 26rpx;
	}

	.order-card-header {
		height: 80rpx;
	}

	.pay-box {
		.discounts-title {
			font-size: 24rpx;
			color: #999;
		}

		.discounts-money {
			font-size: 24rpx;
			color: #333;
		}
	}

	.order-card-footer {
		height: 100rpx;
	}

	.list-item {
		position: relative;
		background: #fff;
		padding: 10px;
		border: 1px solid #eee;
		margin-bottom: 10px;
		border-radius: 5px;
		overflow: hidden;
	}

	/* 状态徽章样式 */
	.status-container {
		position: absolute;
		top: 70px;
		right: -45px;
		width: 45%;
		height: 25px;
		transform: rotate(45deg);
		z-index: 1;
		background-color: transparent;
	}

	.status-badge {
		width: 100%;
		height: 100%;
		text-align: center;
		line-height: 25px;
		font-size: 12px;
		color: #fff;
		font-weight: bold;
		white-space: nowrap;
		display: block;
	}

	.status-badge.unaudited {
		background-color: #2e70fc;
	}

	.status-badge.audited {
		background-color: #00c300;
	}

	.status-badge.unshipped {
		background-color: #d2c200;
	}

	.status-badge.shipped {
		background-color: #34f700;
	}

	.status-badge.unpaid {
		background-color: #9c27b0;
	}

	.status-badge.paid {
		background-color: #00fa00;
	}
</style>